'use strict';
// Copyright 2014 Blueant Inc. All Rights Reserved.

/**
 * @fileoverview 战斗排行版
 * @author sundbcn@gmail.com (sun debing)
 */

var _ = require('lodash');
var async = require('async');
var roleModel = require('../models/roleModel');
var arenaModel = require('../models/arenaModel');
var battleModel = require('../models/battleModel');
var PlayerManager = require('../libs/playerManager');
var unionGroupModel = require('../models/unionGroupModel');
var roleService = require('./roleService.js');
var mailService = require('./mailService.js');
var arenaConf = require('../config/arenaConf.js');
var langUtil = require('../util/langUtil');
var moduleType = require('../consts/moduleType');
var operationType = require('../consts/operationType');

/**
 * 查询竞技场排行版
 * @param {[type]} battle_list [description]
 */
exports.getArenaRank = function (cb) {
    _getArenaRankInfo(cb);
};

/**
 * 获取玩家伤害名
 */
exports.getCurrentRoleArenaRank = function (role_id, cb) {
    _getRoleArenaRank(role_id, cb);
};

/**
 * 当前玩家排名
 */
var _getRoleArenaRank = function (role_id, callback) {
    var arena_model;
    var current_role_info = {};
    async.waterfall(
        [
            function (cb) {
                arenaModel.getByRoleId(role_id, cb);
            },
            function (model, cb) {
                arena_model = model;
                _getRoleInfo(arena_model, cb);
            },
            function (role_info, cb) {
                current_role_info = role_info;
                current_role_info.fight_power = arena_model.att_power;
                current_role_info.rank = arena_model.rank;
                cb();
            }
        ],
        function (err) {
            if (!!err) {
                console.error(err);
            }
            callback(null, current_role_info);
        }
    );
};

/**
 * 排行版相关信息
 */
var _getArenaRankInfo = function (cb) {
    arenaModel.findTop(50, function (err, top_role_list) {
        var top_list = [];
        async.eachSeries(top_role_list, function (role_item, cb) {
            if (role_item.npc_id === 0) {
                _getRivalRoleInfo(role_item.role_id, role_item.def_soldier_list, function (err, role_info) {
                    if (!!role_info) {
                        var result_item = _.clone(role_info, true);
                        result_item.rank = role_item.rank;
                        result_item.fight_power = role_item.att_power;
                        top_list.push(result_item);
                    } else {
                        console.error('not found', role_item.role_id);
                    }
                    cb();
                });
            } else {
                _getNpcInfo(role_item.npc_id, function (err, npc_info) {
                    npc_info.rank = role_item.rank;
                    npc_info.fight_power = role_item.att_power;
                    top_list.push(npc_info);
                    cb();
                });
            }
        }, function (err) {
            if (!!err) {
                console.error(err);
                return cb(err);
            }
            cb(null, top_list);
        });
    });
};

/**
 * 取出角色相关信息
 */
var _getRivalRoleInfo = function (role_id, soldier_type_list, callback) {
    var rival_player_manager = new PlayerManager(role_id);
    var soldier_list = [];
    var rival_info;
    async.waterfall(
        [
            function (cb) {
                rival_player_manager.getModel(['soldier', 'accrued'], cb);
            },
            function (cb) {
                var soldier_model = rival_player_manager.soldier;
                _.forEach(soldier_type_list, function (soldier_type) {
                    if (soldier_type > 0) {
                        var soldier_info = soldier_model.getSoldier(soldier_type);
                        if (!!soldier_info) {
                            soldier_list.push({
                                soldier_type: soldier_type,
                                soldier_lvl: soldier_info.lv,
                                soldier_star: soldier_info.star
                            });
                        } else {
                            console.warn('invalid soldier_type:', soldier_type);
                        }
                    }
                });
                cb();
            },
            function (cb) {
                roleService.getRoleInfo(role_id, cb);
            },
            function (info, cb) {
                rival_info = info;
                rival_info.soldier_list = soldier_list;
                cb();
            }
        ],
        function (err) {
            if (!!err) {
                return callback(err);
            }

            return callback(null, rival_info);
        }
    );
};

/**
 * 取出NPC信息
 */
var _getNpcInfo = function (npc_id, callback) {
    var rival_info = {};
    var npc_info = arenaConf.getArenaConf(npc_id);
    rival_info.role_id = npc_id;
    rival_info.name = npc_info.name;
    rival_info.lv = npc_info.lvl;
    rival_info.job_type = npc_info.job_type;

    rival_info.soldier_list = _getSoldierTypeLvlList(npc_info.soldier_info);

    callback(null, rival_info);
};

/**
 * 获取士兵类型与等级信息
 * @return {Array} [description]
 */
var _getSoldierTypeLvlList = function (soldier_info_str) {
    var soldier_type_list = [];
    if (soldier_info_str.length <= 0) {
        return soldier_type_list;
    }

    var soldier_info_list = soldier_info_str.split(',');
    _.forEach(soldier_info_list, function (soldier_info_item) {
        var soldier_info = soldier_info_item.split(':');
        var soldier_type = parseInt(soldier_info[0]);
        var soldier_lvl = parseInt(soldier_info[1]);
        var soldier_star = parseInt(soldier_info[2]);

        soldier_type_list.push({
            soldier_type: soldier_type,
            soldier_lvl: soldier_lvl,
            soldier_star: soldier_star
        });
    });
    return soldier_type_list;
};

/**
 * 玩家信息
 */
var _getRoleInfo = function (role_item, cb) {
    roleService.getRoleInfo(role_item.role_id, function (err, role_info) {
        if (!!role_info) {
            cb(null, _.clone(role_info, true));
        } else {
            console.error('not found', role_item.role_id);
            cb(null, role_item);
        }
    });
};

/**
 * 发送排名奖励
 */
exports.sendRankReward = function (cb) {
    var max_rank = arenaConf.getMaxRank();
    var count = 0;
    arenaModel.findPlayerByRankRange(1, max_rank, function (err, rank_list) {
        if (!!err) {
            console.error(err);
            if (!!cb) {
                cb();
            }
            return;
        }

        var rank_conf = arenaConf.getRangeConf(1);
        if (!rank_conf) {
            console.error('配置表无效，排名[1]');
            if (!!cb) {
                cb();
            }
            return;
        }

        async.eachSeries(rank_list, function (rank_info, callback) {
            count++;
            if (rank_info.rank < rank_conf[0].min_cup || rank_conf[0].max_cup < rank_info.rank) {
                rank_conf = arenaConf.getRangeConf(rank_info.rank);
            }

            if (!rank_conf[0]) {
                console.error('配置表无效，排名[%j]', rank_info.rank);
                callback();
                return true;
            }

            var player_manager = new PlayerManager(rank_info.role_id);
            player_manager.getModel(['mail', 'accrued'], function (err) {
                var mail_model = player_manager.mail;
                var title = langUtil.getString('arena_rank_reward_mail_title');
                var content = langUtil.getString('arena_rank_reward_mail_content');
                var reward_list = [];
                _.forEach(rank_conf, function (reward_info) {
                    reward_list.push({
                        reward: reward_info.reward,
                        reward_type: reward_info.reward_type,
                        reward_num: reward_info.reward_num,
                        reward_value: reward_info.reward_value,
                        hole_num: reward_info.hole_num
                    });
                });
                console.log('----send reward mail:', reward_list);
                mailService.sendMail(mail_model, title, content, reward_list, moduleType.MDL_ARENA, operationType.OPR_ARENA_RANK_REWARD);
                player_manager.save(callback);
            });
        }, function (err) {
            if (!!err) {
                console.error('sendHonorRankReward error:', err);
            }

            if (!!cb) {
                cb(null, count);
            }
        });
    });
};
